
import React, { useState, useEffect } from "react";
import "./App.css";
import KanbanBoard, {
  COLUMN_KEY_DONE,
  COLUMN_KEY_ONGOING,
  COLUMN_KEY_TODO,
} from "./KanbanBoard";
import AdminContext from "./AdminContext";

const DATA_STORE_KEY = "kanban-data-store";

function App() {
  const [isLoading, setIsLoading] = useState(true);
  const [isAdmin,setIsAdmin] = useState(false)
  const [todoList, setTodoList] = useState([
    { title: "开发任务-1", status: "2023-05-21 18:15" },
    { title: "开发任务-3", status: "2023-05-22 18:15" },
    { title: "开发任务-5", status: "2023-05-24 18:15" },
    { title: "测试任务-3", status: "2023-06-08 12:15" },
  ]);
  const [ongoingList, setOngoingList] = useState([
    { title: "开发任务-4", status: "2023-06-02 18:15" },
    { title: "开发任务-6", status: "2023-06-02 18:15" },
    { title: "测试任务-2", status: "2023-06-02 18:15" },
  ]);
  const [doneList, setDoneList] = useState([
    { title: "开发任务-2", status: "2023-06-09 15:15" },
    { title: "测试任务-1", status: "2023-06-09 13:15" },
  ]);
  useEffect(() => {
    const data = window.localStorage.getItem(DATA_STORE_KEY);
    setTimeout(() => {
      if (data) {
        const kanbanColumnData = JSON.parse(data);
        setDoneList(kanbanColumnData.doneList);
        setOngoingList(kanbanColumnData.ongoingList);
        setTodoList(kanbanColumnData.todoList);
      }
      setIsLoading(false);
    }, 1000);
  }, []);

  //保存全部
  const handleSaveAll = () => {
    const data = JSON.stringify({
      todoList,
      ongoingList,
      doneList,
    });
    window.localStorage.setItem(DATA_STORE_KEY, data);
  };
  const updates = {
    [COLUMN_KEY_TODO]: setTodoList,
    [COLUMN_KEY_ONGOING]: setOngoingList,
    [COLUMN_KEY_DONE]: setDoneList,
  };

  const handleOnAdd = (column, newCard) => {
    updates[column]((current) => [newCard, ...current]);
  };
  const handleOnRemove = (column, draggedItem) => {
    updates[column]((current) =>
      current.filter((item) => item.title!== draggedItem.title  )
    );
  };
  const handleAdmin = ()=>{
    setIsAdmin(current=>!current)
  }
  return (
    <div className="App">
      <header className="App-header">
        <h1>
          我的看板<button onClick={handleSaveAll}>保存所有卡片</button>
          <label>
            <input type="checkbox" value={isAdmin} onChange={handleAdmin}/>管理员模式
          </label>
        </h1>

      </header>
      <AdminContext.Provider value={isAdmin}>
      <KanbanBoard
        isLoading={isLoading}
        todoList={todoList}
        ongoingList={ongoingList}
        doneList={doneList}
        onAdd={handleOnAdd}
        onRemove={handleOnRemove}
      />
      </AdminContext.Provider>
    </div>
  );
}

export default App;
